#pragma once
#include <iostream>
#include <string.h>
#include <stdlib.h>

namespace bit
{
    class string
    {
    private:
        char *_str;
        size_t _size;
        size_t _capacity;

    public:
        friend std::ostream &operator<<(std::ostream &out, bit::string &s);
        static size_t npos;
        string()
            : _size(0),
              _str(nullptr),
              _capacity(0)
        {
            _str = (char *)malloc(1);
            _str[0] = '\0';
        }
        string (const char* s)
            :_size(0),
            _str(nullptr),
            _capacity(0)
        {
            int len = strlen(s);
            resize(len+1);
            strcpy(_str,s);
            _str[len] = 0;
        }
        
        string(size_t n, char c = '\0')
            : _size(0),
            _str(nullptr),
              _capacity(0)
        {
            resize(n, c);
        }
        const char *c_str()
        {
            return _str;
        }
        void resize(size_t n, char c = '\0')
        {
            if (n >= _size)
            {
                char *tmp = (char *)realloc(_str, n + 1);
                if (_str)
                    strcpy(tmp, _str);
                while (_size < n)
                {
                    tmp[_size++] = c;
                }
                tmp[_size] = '\0';
                _str = tmp;
                _size = _capacity = n;
            }
            else
            {
                _str[_size] = '\0';
                _size = n;
            }
        }

        // 拷贝构造
    };

    size_t bit::string::npos = -1;
    std::ostream &operator<<(std::ostream &out, bit::string &s)
    {
        std::cout << s.c_str();
        return out;
    }
    std::istream &operator>>(std::istream &in, bit::string &s)
    {
        std::cin >> s;
        return in;
    }
}
